package com.itfreer.arcgis.utils;

import com.esri.arcgisruntime.data.Geodatabase;
import com.esri.arcgisruntime.data.GeodatabaseFeatureTable;
import com.esri.arcgisruntime.loadable.LoadStatus;
import com.esri.arcgisruntime.mapping.view.MapView;
import com.itfreer.utils.common.LogUtils;
import com.itfreer.utils.common.ToastUtils;

import java.util.List;

/**
 * 空间数据库操作辅助类
 */
public class GeodatabaseUtils {

    /**
     * 加载数据库
     */
    public void loadGeodatabase(final MapView mMapView, String path) {
        final Geodatabase geodatabase = GeodatabaseUtils.GetGeodatabaseByPath(path);
        geodatabase.loadAsync();
        geodatabase.addDoneLoadingListener(new Runnable() {
            @Override
            public void run() {
                if (geodatabase.getLoadStatus() == LoadStatus.LOADED) {
                    List<GeodatabaseFeatureTable> geodatabaseFeatureTables = GeodatabaseUtils
                            .GetAllFeatureTables(geodatabase);
                    if (geodatabaseFeatureTables == null || geodatabaseFeatureTables.size() == 0)
                        return;

                    for (int i = 0; i < geodatabaseFeatureTables.size(); i++) {
                        GeodatabaseFeatureTable geodatabaseFeatureTable = geodatabaseFeatureTables.get(i);
                        geodatabaseFeatureTable.loadAsync();
                        // 添加图层到地图中
                        MapUtils.AddGeodatabaseFeatureTable(mMapView, geodatabaseFeatureTable, true, "");
                    }
                } else {
                    LogUtils.Print("数据库加载失败！", LogUtils.Lever.Info);
                }
            }
        });
    }

    /**
     * 根据名称获取空间表对象
     * @param geodatabase 数据库对象
     * @param name 空间表名称
     * @return 空间表对象
     */
    public static GeodatabaseFeatureTable GetGeodatabaseFeatureTableByName(Geodatabase geodatabase,String name) {
        GeodatabaseFeatureTable geodatabaseFeatureTable  = geodatabase.getGeodatabaseFeatureTable(name);
        return geodatabaseFeatureTable;
    }

    /**
     * 根据路径获取数据库对象
     * @param path 路径
     * @return
     */
    public static Geodatabase GetGeodatabaseByPath(String path) {
        Geodatabase geodatabase = new Geodatabase(path);
        geodatabase.loadAsync();
        return  geodatabase;
    }

    /**
     * 获取数据库中所有的矢量图层
     * @param geodatabase
     * @return
     */
    public static List<GeodatabaseFeatureTable> GetAllFeatureTables(Geodatabase geodatabase) {
        return geodatabase.getGeodatabaseFeatureTables();
    }
}
